<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          clearable
          size="small"
          placeholder="请选择状态"
        >
          <el-option
            v-for="dict in searchOption"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="openForm()"
          v-hasPermi="['store:category:create']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['store:category:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >
          展开/折叠
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      v-if="refreshTable"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column
        label="类型"
        align="center"
        prop="type"
        :formatter="formatType"
      />
      <el-table-column label="分类图标" align="center" prop="extra" width="100"
        ><template slot-scope="scope">
          <image-preview
            :src="scope.row.extra"
            :width="50"
            :height="50"
          /> </template
      ></el-table-column>
      <el-table-column
        label="状态"
        align="center"
        min-width="150"
        prop="status"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="onchangeIsShow(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="openForm(scope.row)"
            v-hasPermi="['store:category:update']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['store:category:delete']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 对话框(添加 / 修改) -->
    <CategoryForm
      ref="formRef"
      @success="getList"
      @updateCategorys="handleUpdateCategory"
    />
  </div>
</template>

<script>
import * as CategoryApi from "@/api/store/category";
import CategoryForm from "./CategoryForm.vue";
export default {
  name: "Category",
  components: {
    CategoryForm,
  },
  data() {
    return {
      //下拉框选项
      searchOption: [
        { value: 1, label: "显示" },
        { value: 0, label: "不显示" },
      ],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 商品分类列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      // 查询参数
      queryParams: {
        name: null,
        status: 1,
      },
      updateStatus: {
        id: null,
        status: null,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleUpdateCategory(updatedChildren) {
      // 处理更新逻辑
      this.recursiveUpdateChildren(updatedChildren);
    },
    // 状态变更的核心方法：递归更新子节点状态
    onchangeIsShow(row) {
      this.loading = true; // 开始加载
      // 1. 更新当前节点状态到后端
      this.updateCategoryStatus(row.id, row.status)
        .then(() => {
          this.$modal.msgSuccess("状态更新成功");
          // 2. 递归更新所有子节点状态
          this.recursiveUpdateChildren(row);
        })
        .finally(() => {
          this.loading = false; // 结束加载
        });
    },
    // 递归更新子节点状态
    recursiveUpdateChildren(parentNode) {
      if (parentNode.children && parentNode.children.length > 0) {
        parentNode.children.forEach((child) => {
          // 更新子节点状态
          child.status = parentNode.status;
          // 同步到后端
          this.updateCategoryStatus(child.id, child.status).then(() => {
            // 递归处理子节点的子节点
            this.recursiveUpdateChildren(child);
          });
        });
      }
    },
    // 调用接口更新状态（封装成方法）
    async updateCategoryStatus(id, status) {
      this.updateStatus.id = id;
      this.updateStatus.status = status;
      await CategoryApi.updateCategory(this.updateStatus).then(() => {
        this.getList();
      });
    },
    formatType(row, column, cellValue) {
      return cellValue === 1 ? "产品分类" : cellValue;
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await CategoryApi.getCategoryList(this.queryParams);
        // console.log(JSON.stringify(res, 0, 2));

        this.list = this.handleTree(res.data, "id", "pid");
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm(
        '是否确认删除商品分类编号为"' + id + '"的数据项?'
      );
      try {
        await CategoryApi.deleteCategory(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {}
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm("是否确认导出所有商品分类数据项?");
      try {
        this.exportLoading = true;
        const data = await CategoryApi.exportCategoryExcel(this.queryParams);
        this.$download.excel(data, "商品分类.xls");
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(function () {
        this.refreshTable = true;
      });
    },
  },
};
</script>
